import Sprite from './base/sprite.js'
import DataBus from './databus.js'

const screenWidth = window.innerWidth
const screenHeight = window.innerHeight

const PLAYER_IMG_SRC = 'images/player1.png'
const PLAYER_WIDTH = 100
const PLAYER_HEIGHT = 20

export default class Player extends Sprite {
  constructor(mode) {
    super(PLAYER_IMG_SRC, PLAYER_WIDTH, PLAYER_HEIGHT)

    // 游戏模式
    this.mode = mode
    // 玩家默认处于屏幕底部居中位置
    this.PLAYER_WIDTH = PLAYER_WIDTH
    this.PLAYER_HEIGHT = PLAYER_HEIGHT
    this.x = screenWidth / 2 - this.width / 2
    this.y = screenHeight - this.height - 60

    // 用于在手指移动的时候标识手指是否已经在飞机上了
    this.touched = false

    // 初始化事件监听
    this.initEvent()
  }


  initEvent() {
    canvas.addEventListener('touchstart', ((e) => {
      e.preventDefault()

      let x = e.touches[0].clientX
      let y = e.touches[0].clientY

      //
      if (this.checkIsFingerOnAir(x, y)) {
        this.touched = true

        this.setAirPosAcrossFingerPosZ(x, y)
      }

    }).bind(this))

    canvas.addEventListener('touchmove', ((e) => {
      e.preventDefault()

      let x = e.touches[0].clientX
      let y = e.touches[0].clientY

      if (this.touched)
        this.setAirPosAcrossFingerPosZ(x, y)

    }).bind(this))

    canvas.addEventListener('touchend', ((e) => {
      e.preventDefault()

      this.touched = false
    }).bind(this))
  }


  /**
   * 当手指触摸屏幕的时候
   * 判断手指是否在飞机上
   * @param {Number} x: 手指的X轴坐标
   * @param {Number} y: 手指的Y轴坐标
   * @return {Boolean}: 用于标识手指是否在飞机上的布尔值
   */
  checkIsFingerOnAir(x, y) {
    const deviation = 30

    return !!(x >= this.x - deviation
      && y >= this.y - deviation
      && x <= this.x + this.width + deviation
      && y <= this.y + this.height + deviation)
  }

  /**
   * 根据手指的位置设置飞机的位置
   * 保证手指处于飞机中间
   * 同时限定飞机的活动范围限制在屏幕中
   */
  setAirPosAcrossFingerPosZ(x, y) {
    // 触摸点的位置，转换为托盘左上角的坐标
    let disX = x - this.width / 2
    let disY = y - this.height / 2

    
    // 超出屏幕左边
    if (disX < 0)
      disX = 0

    // 超出屏幕右边
    else if (disX > screenWidth - this.width)
      disX = screenWidth - this.width

    // 超出屏幕以上
    if (disY <= 0)
      disY = 0

    // 超出屏幕以下
    else if (disY > screenHeight - this.height)
      disY = screenHeight - this.height

    if (this.mode == 'nomal'){
      if (disY <= screenHeight - this.height){
        disY = screenHeight - this.height-40
      }
    }

    this.x = disX
    this.y = disY - 20
    
  }
  
}